#include "employeemanager.h"
#include <QDebug>
#include <QDateTime>
#include <QVariantHash>
#include <QCoreApplication>

EmployeeManager::EmployeeManager(QObject *parent) : QObject(parent),
    m_dbOperator(new SqlOperator()),
    m_ownsDbOperator(true)
{
    initDatabase();
}

EmployeeManager::~EmployeeManager()
{
    closeDatabase();
    if (m_dbOperator && m_ownsDbOperator)
    {
        delete m_dbOperator;
        m_dbOperator = nullptr;
    }
}

bool EmployeeManager::initDatabase()
{
    QString appDir = QCoreApplication::applicationDirPath();
    QString dbPath = appDir + "/../../sql/company.db";
    if (!m_dbOperator->open(dbPath, "employeeManagerConnection"))
    {
        emit operationResult(false, "无法连接到数据库: " + m_dbOperator->lastError());
        return false;
    }
    return true;
}

void EmployeeManager::closeDatabase()
{
    if (m_dbOperator && m_dbOperator->isOpen())
    {
        m_dbOperator->close();
    }
}
//查询员工自己信息
QMap<QString, QString> EmployeeManager::getEmployeeInfo(const QString &empId)
{
    QMap<QString, QString> employeeInfo;

    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        if (!initDatabase())
        {
            emit operationResult(false, "数据库连接失败");
            return employeeInfo;
        }
    }

    // 查询员工信息的SQL语句
    QString sql = QString("SELECT e.emp_id, e.emp_name, e.gender, e.position, d.dept_name "
                          "FROM employee e "
                          "JOIN department d ON e.dept_id = d.dept_id "
                          "WHERE e.emp_id = '%1'").arg(empId);

    // 定义要查询的字段
    QList<QString> fields = {"emp_id", "emp_name", "gender", "position", "dept_name"};
    QList<QVariantList> data;

    // 执行查询
    if (!m_dbOperator->selectDataBySql(sql, fields, data)) {
        emit operationResult(false, "查询员工信息失败: " + m_dbOperator->lastError());
        return employeeInfo;
    }

    // 处理查询结果
    if (!data.isEmpty()) {
        QVariantList rowData = data.first();
        employeeInfo["emp_id"] = rowData[0].toString();
        employeeInfo["emp_name"] = rowData[1].toString();
        employeeInfo["gender"] = rowData[2].toString();
        employeeInfo["position"] = rowData[3].toString();
        employeeInfo["dept_name"] = rowData[4].toString();
        emit operationResult(true, "查询员工信息成功");
    } else {
        emit operationResult(false, "未找到员工信息");
    }

    return employeeInfo;
}
//签到
bool EmployeeManager::checkIn(const QString &empId)
{
    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        if (!initDatabase())
        {
            emit operationResult(false, "数据库连接失败");
            return false;
        }
    }

    // 获取当前日期和时间
    QString currentDate = QDateTime::currentDateTime().toString("yyyy-MM-dd");
    QString currentTime = QDateTime::currentDateTime().toString("HH:mm:ss");

    // 检查当天是否已经签到
    QList<QString> fields = {"record_id"};
    QHash<QString, QVariant> whereConditions;
    whereConditions.insert("emp_id", empId);
    whereConditions.insert("date", currentDate);
    QList<QVariantList> data;

    if (m_dbOperator->selectData("attendance", fields, whereConditions, data)) {
        if (!data.isEmpty()) {
            emit checkStatusUpdated("您今天已经签到");
            return false;
        }
    } else {
        emit operationResult(false, "检查签到记录失败: " + m_dbOperator->lastError());
        return false;
    }

    // 插入签到记录
    fields = {"emp_id", "check_in_time", "date", "status"};
    QVariantList values;
    values << empId << currentTime << currentDate << "正常";

    bool result = m_dbOperator->insertRowData("attendance", fields, values);

    if (result) {
        emit operationResult(true, "签到记录插入成功");
        // 检查是否迟到（假设上班时间为09:00）
        if (currentTime > "09:00:00") {
            QString updateSql = QString("UPDATE attendance SET status = '迟到' WHERE emp_id = '%1' AND date = '%2'").arg(empId).arg(currentDate);
            if (m_dbOperator->exec(updateSql)) {
                emit checkStatusUpdated("签到成功，但已迟到");
            } else {
                emit operationResult(false, "更新签到状态失败: " + m_dbOperator->lastError());
            }
        } else {
            emit checkStatusUpdated("签到成功");
        }
    } else {
        emit operationResult(false, "插入签到记录失败: " + m_dbOperator->lastError());
    }

    return result;
}
//签退
bool EmployeeManager::checkOut(const QString &empId)
{
    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        if (!initDatabase())
        {
            emit operationResult(false, "数据库连接失败");
            return false;
        }
    }

    // 获取当前日期和时间
    QString currentDate = QDateTime::currentDateTime().toString("yyyy-MM-dd");
    QString currentTime = QDateTime::currentDateTime().toString("HH:mm:ss");

    // 检查当天是否有签到记录且未签退
    QList<QString> fields = {"record_id", "status"};
    QHash<QString, QVariant> whereConditions;
    whereConditions.insert("emp_id", empId);
    whereConditions.insert("date", currentDate);
    //whereConditions.insert("check_out_time", QVariant(QVariant::String)); // 查找check_out_time为NULL的记录
    QList<QVariantList> data;

    if (!m_dbOperator->selectData("attendance", fields, whereConditions, data)) {
        emit operationResult(false, "查询签到记录失败: " + m_dbOperator->lastError());
        emit checkStatusUpdated("未找到有效的签到记录");
        return false;
    }

    if (data.isEmpty()) {
        emit checkStatusUpdated("未找到有效的签到记录或已经签退");
        return false;
    }

    int recordId = data[0][0].toInt();
        QString originalStatus = data[0][1].toString();
        QString updateSql = QString("UPDATE attendance SET check_out_time = '%1' WHERE record_id = %2").arg(currentTime).arg(recordId);
        bool result = m_dbOperator->exec(updateSql);

        // 检查是否早退（假设下班时间为18:00）
        if (result) {
            if (currentTime < "18:00:00") {
                if (originalStatus == "迟到") {
                    QString newStatus = "迟到且早退";
                    emit checkStatusUpdated("签退成功，今日迟到且早退");
                    updateSql = QString("UPDATE attendance SET status = '%1' WHERE record_id = %2").arg(newStatus).arg(recordId);
                    m_dbOperator->exec(updateSql);
                } else {
                    QString newStatus = "早退";
                    emit checkStatusUpdated("签退成功，但已早退");
                    updateSql = QString("UPDATE attendance SET status = '%1' WHERE record_id = %2").arg(newStatus).arg(recordId);
                    m_dbOperator->exec(updateSql);
                }
            } else {
                // 如果原本是正常，保持正常；如果原本是迟到，保持迟到
                emit checkStatusUpdated(originalStatus == "正常" ? "签退成功" : "签退成功，今日迟到");
            }}
            else {
        emit operationResult(false, "更新签退时间失败: " + m_dbOperator->lastError());
    }

    return result;
}
//获取打卡记录
QVariantList EmployeeManager::getAttendanceRecord(const QString &empId, const QString &date)
{
    QVariantList record;

    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        if (!initDatabase())
        {
            emit operationResult(false, "数据库连接失败");
            return record;
        }
    }

    // 查询打卡记录
    QList<QString> fields = {"check_in_time", "check_out_time", "status"};
    QHash<QString, QVariant> whereConditions;
    whereConditions.insert("emp_id", empId);
    whereConditions.insert("date", date);
    QList<QVariantList> data;

    if (m_dbOperator->selectData("attendance", fields, whereConditions, data)) {
        if (!data.isEmpty()) {
            record = data[0];
            emit operationResult(true, "查询打卡记录成功");
        } else {
            emit operationResult(false, "未找到打卡记录");
        }
    } else {
        emit operationResult(false, "查询打卡记录失败: " + m_dbOperator->lastError());
    }

    return record;
}
//调岗申请
bool EmployeeManager::submitDepartmentChangeRequest(const QString &empId, int newDeptId, const QString &reason)
{
    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        if (!initDatabase())
        {
            emit operationResult(false, "数据库连接失败");
            return false;
        }
    }

    // 获取当前员工的原部门ID
    QString currentDeptIdQuery = QString("SELECT dept_id FROM employee WHERE emp_id = '%1'").arg(empId);
    QList<QString> fields = {"dept_id"};
    QList<QVariantList> data;

    if (!m_dbOperator->selectDataBySql(currentDeptIdQuery, fields, data) || data.isEmpty()) {
        emit operationResult(false, "获取当前部门ID失败");
        return false;
    }

    int oldDeptId = data[0][0].toInt();
    QString currentTime = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");

    // 插入调岗申请
    fields = {"emp_id", "old_dept_id", "new_dept_id", "reason", "request_time", "status"};
    QVariantList values;
    values << empId << oldDeptId << newDeptId << reason << currentTime << "未审核";

    bool result = m_dbOperator->insertRowData("transfer_request", fields, values);

    if (result) {
        emit operationResult(true, "调岗申请提交成功");
    } else {
        emit operationResult(false, "调岗申请提交失败: " + m_dbOperator->lastError());
    }

    return result;
}
//撤销调岗申请
bool EmployeeManager::cancelDepartmentChangeRequest(int requestId)
{
    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        if (!initDatabase())
        {
            emit operationResult(false, "数据库连接失败");
            return false;
        }
    }

    // 更新申请状态为已撤销
    QHash<QString, QVariant> updateData;
    updateData.insert("status", "已撤销");
    //updateData.insert("cancel_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));

    QHash<QString, QVariant> whereConditions;
    whereConditions.insert("request_id", requestId);

    bool result = m_dbOperator->updateData("transfer_request", updateData, whereConditions);

    if (result) {
        emit operationResult(true, "调岗申请撤销成功");
    } else {
        emit operationResult(false, "调岗申请撤销失败: " + m_dbOperator->lastError());
    }

    return result;
}
//请假申请
bool EmployeeManager::submitLeaveRequest(const QString &empId, const QString &leaveType, const QString &startDate, const QString &endDate, const QString &reason)
{
    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        if (!initDatabase())
        {
            emit operationResult(false, "数据库连接失败");
            return false;
        }
    }

    // 获取当前时间
    QString currentTime = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");

    // 插入请假申请
    QList<QString> fields = {"emp_id", "leave_type", "start_date", "end_date", "reason", "request_time", "status"};
    QVariantList values;
    values << empId << leaveType << startDate << endDate << reason << currentTime << "未审核";

    bool result = m_dbOperator->insertRowData("leave_request", fields, values);

    if (result) {
        emit operationResult(true, "请假申请提交成功");
    } else {
        emit operationResult(false, "请假申请提交失败: " + m_dbOperator->lastError());
    }

    return result;
}
//撤销请假申请
bool EmployeeManager::cancelLeaveRequest(int requestId)
{
    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        if (!initDatabase())
        {
            emit operationResult(false, "数据库连接失败");
            return false;
        }
    }

    // 查询申请是否存在且状态为未审核
    QList<QString> fields = {"request_id"};
    QHash<QString, QVariant> whereConditions;
    whereConditions.insert("request_id", requestId);
    whereConditions.insert("status", "未审核");
    QList<QVariantList> data;

    if (!m_dbOperator->selectData("leave_request", fields, whereConditions, data)) {
        emit operationResult(false, "查询请假申请失败: " + m_dbOperator->lastError());
        return false;
    }

    if (data.isEmpty()) {
        emit operationResult(false, "未找到有效的请假申请");
        return false;
    }

    // 更新请假申请状态为已撤销
    QHash<QString, QVariant> updateData;
    updateData.insert("status", "已撤销");
    //updateData.insert("cancel_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));

    bool result = m_dbOperator->updateData("leave_request", updateData, whereConditions);

    if (result) {
        emit operationResult(true, "请假申请撤销成功");
    } else {
        emit operationResult(false, "请假申请撤销失败: " + m_dbOperator->lastError());
    }

    return result;
}
//查看工资详情
QVariantList EmployeeManager::getSalaryDetails(const QString &empId)
{
    QVariantList salaryDetails;

    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        if (!initDatabase())
        {
            emit operationResult(false, "数据库连接失败");
            return salaryDetails;
        }
    }

    // 查询工资详情的SQL语句
    QString sql = QString("SELECT * FROM salary WHERE emp_id = '%1' ORDER BY payment_date DESC").arg(empId);

    // 定义要查询的字段
    QList<QString> fields = {"salary_id", "emp_id", "basic_salary", "deduction", "actual_salary", "payment_date", "payment_period"};
    QList<QVariantList> data;

    // 执行查询
    if (!m_dbOperator->selectDataBySql(sql, fields, data)) {
            emit operationResult(false, "查询工资详情失败: " + m_dbOperator->lastError());
            return salaryDetails;
        }

        // 将查询结果转换为QVariantList
        for (const QVariantList &row : data) {
            QVariantHash salaryInfo;
            salaryInfo["salary_id"] = row[0];
            salaryInfo["emp_id"] = row[1];
            salaryInfo["basic_salary"] = row[2];
            salaryInfo["deduction"] = row[3];
            salaryInfo["actual_salary"] = row[4];
            salaryInfo["payment_date"] = row[5];
            salaryInfo["payment_period"] = row[6];
            salaryDetails.append(salaryInfo);
        }

        if (salaryDetails.isEmpty()) {
            emit operationResult(false, "未找到工资记录");
        } else {
            emit operationResult(true, QString("成功查询到 %1 条工资记录").arg(salaryDetails.size()));
        }

        return salaryDetails;
}
// 获取考核详情
QVariantList EmployeeManager::getAssessmentDetails(const QString &empId)
{
    QVariantList assessmentDetails;

    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        if (!initDatabase())
        {
            emit operationResult(false, "数据库连接失败");
            return assessmentDetails;
        }
    }

    // 查询考核详情的SQL语句，包含新字段
    QString sql = QString("SELECT eval_id, emp_id, late_count, leave_count, early_leave_count, late_and_leave_count, absent_count, score, eval_period FROM evaluation WHERE emp_id = '%1' ORDER BY eval_period DESC")
                      .arg(empId);

    // 定义要查询的字段，包含新字段
    QList<QString> fields = {"eval_id", "emp_id", "late_count", "leave_count", "early_leave_count", "late_and_leave_count", "absent_count", "score", "eval_period"};
    QList<QVariantList> data;

    // 执行查询
    if (!m_dbOperator->selectDataBySql(sql, fields, data)) {
        emit operationResult(false, "查询考核详情失败: " + m_dbOperator->lastError());
        return assessmentDetails;
    }

    // 处理查询结果，添加新字段的值
    foreach (const QVariantList &rowData, data) {
        QVariantHash assessmentInfo;
        assessmentInfo["eval_id"] = rowData[0];
        assessmentInfo["emp_id"] = rowData[1];
        assessmentInfo["late_count"] = rowData[2];
        assessmentInfo["leave_count"] = rowData[3];
        assessmentInfo["early_leave_count"] = rowData[4];
        assessmentInfo["late_and_leave_count"] = rowData[5];
        assessmentInfo["absent_count"] = rowData[6];
        assessmentInfo["score"] = rowData[7];
        assessmentInfo["eval_period"] = rowData[8];
        assessmentDetails.append(assessmentInfo);
    }

    if (!assessmentDetails.isEmpty()) {
        emit operationResult(true, "查询考核详情成功");
    } else {
        emit operationResult(false, "未找到考核记录");
    }

    return assessmentDetails;
}

// 根据日期范围获取考核详情
QVariantList EmployeeManager::getAssessmentDetailsByDateRange(const QString &empId, const QString &startDate, const QString &endDate)
{
    QVariantList assessmentDetails;

    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        if (!initDatabase())
        {
            emit operationResult(false, "数据库连接失败");
            return assessmentDetails;
        }
    }

    // 查询考核详情的SQL语句（根据eval_period字段筛选），包含新字段
    QString sql = QString("SELECT eval_id, emp_id, late_count, leave_count, early_leave_count, late_and_leave_count, absent_count, score, eval_period FROM evaluation WHERE emp_id = '%1' AND eval_period BETWEEN '%2' AND '%3' ORDER BY eval_period DESC")
                      .arg(empId).arg(startDate).arg(endDate);

    // 定义要查询的字段，包含新字段
    QList<QString> fields = {"eval_id", "emp_id", "late_count", "leave_count", "early_leave_count", "late_and_leave_count", "absent_count", "score", "eval_period"};
    QList<QVariantList> data;

    // 执行查询
    if (!m_dbOperator->selectDataBySql(sql, fields, data)) {
        emit operationResult(false, "查询考核详情失败: " + m_dbOperator->lastError());
        return assessmentDetails;
    }

    // 处理查询结果，添加新字段的值
    foreach (const QVariantList &rowData, data) {
        QVariantHash assessmentInfo;
        assessmentInfo["eval_id"] = rowData[0];
        assessmentInfo["emp_id"] = rowData[1];
        assessmentInfo["late_count"] = rowData[2];
        assessmentInfo["leave_count"] = rowData[3];
        assessmentInfo["early_leave_count"] = rowData[4];
        assessmentInfo["late_and_leave_count"] = rowData[5];
        assessmentInfo["absent_count"] = rowData[6];
        assessmentInfo["score"] = rowData[7];
        assessmentInfo["eval_period"] = rowData[8];
        assessmentDetails.append(assessmentInfo);
    }

    if (!assessmentDetails.isEmpty()) {
        emit operationResult(true, "查询考核详情成功");
    } else {
        emit operationResult(false, "未找到考核记录");
    }

    return assessmentDetails;
}

// 根据日期范围获取工资详情
QVariantList EmployeeManager::getSalaryDetailsByDateRange(const QString &empId, const QString &startDate, const QString &endDate)
{
    QVariantList salaryDetails;

    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        if (!initDatabase())
        {
            emit operationResult(false, "数据库连接失败");
            return salaryDetails;
        }
    }

    // 验证日期格式 (假设格式为"YYYY-MM-DD")
    QRegExp dateReg("^(19|20)\\d\\d-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$");
    if (!dateReg.exactMatch(startDate) || !dateReg.exactMatch(endDate))
    {
        emit operationResult(false, "日期格式不正确，请使用YYYY-MM-DD格式");
        return salaryDetails;
    }

    // 查询工资详情的SQL语句
    QString sql = QString("SELECT * FROM salary WHERE emp_id = '%1' AND payment_date BETWEEN '%2' AND '%3' ORDER BY payment_date DESC")
                      .arg(empId)
                      .arg(startDate)
                      .arg(endDate);

    // 定义要查询的字段
    QList<QString> fields = {"salary_id", "emp_id", "basic_salary", "deduction", "actual_salary", "payment_date", "payment_period"};
    QList<QVariantList> data;

    // 执行查询
    if (!m_dbOperator->selectDataBySql(sql, fields, data)) {
        emit operationResult(false, "查询工资详情失败: " + m_dbOperator->lastError());
        return salaryDetails;
    }

    // 处理查询结果
    foreach (const QVariantList &rowData, data) {
        QVariantHash salaryInfo;
        salaryInfo["salary_id"] = rowData[0];
        salaryInfo["emp_id"] = rowData[1];
        salaryInfo["basic_salary"] = rowData[2];
        salaryInfo["deduction"] = rowData[3];
        salaryInfo["actual_salary"] = rowData[4];
        salaryInfo["payment_date"] = rowData[5];
        salaryInfo["payment_period"] = rowData[6];
        salaryDetails.append(salaryInfo);
    }

    if (!salaryDetails.isEmpty()) {
        emit operationResult(true, "查询工资详情成功");
    } else {
        emit operationResult(false, "未找到工资详情");
    }

    return salaryDetails;
}
//查询请假申请
QVariantList EmployeeManager::getLeaveRequests(const QString &empId)
{
    QVariantList requests;

    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        if (!initDatabase())
        {
            emit operationResult(false, "数据库连接失败");
            return requests;
        }
    }

    // 查询请假申请
    QString sql = QString("SELECT * FROM leave_request WHERE emp_id = '%1' ORDER BY request_time DESC").arg(empId);

    QList<QString> fields = {"request_id", "emp_id", "leave_type", "start_date", "end_date", "reason", "status", "request_time"};
    QList<QVariantList> data;

    if (m_dbOperator->selectDataBySql(sql, fields, data)) {
        foreach (const QVariantList &row, data) {
            QVariantHash request;
            request.insert("request_id", row[0]);
            request.insert("emp_id", row[1]);
            request.insert("leave_type", row[2]);
            request.insert("start_date", row[3]);
            request.insert("end_date", row[4]);
            request.insert("reason", row[5]);
            request.insert("status", row[6]);
            request.insert("request_time", row[7]);
            requests.append(request);
        }

        if (!requests.isEmpty()) {
            emit operationResult(true, "查询请假申请成功");
        } else {
            emit operationResult(false, "未找到请假申请");
        }
    } else {
        emit operationResult(false, "查询请假申请失败: " + m_dbOperator->lastError());
    }

    return requests;
}
//查询调岗申请
QVariantList EmployeeManager::getDepartmentChangeRequests(const QString &empId)
{
    QVariantList requests;

    // 检查数据库连接
    if (!m_dbOperator->isOpen())
    {
        if (!initDatabase())
        {
            emit operationResult(false, "数据库连接失败");
            return requests;
        }
    }

    // 查询调岗申请
    QString sql = QString("SELECT tr.request_id, tr.old_dept_id, tr.new_dept_id, tr.reason, tr.request_time, tr.status, \
                          d_old.dept_name AS old_dept_name, d_new.dept_name AS new_dept_name \
                          FROM transfer_request tr \
                          JOIN department d_old ON tr.old_dept_id = d_old.dept_id \
                          JOIN department d_new ON tr.new_dept_id = d_new.dept_id \
                          WHERE tr.emp_id = '%1' \
                          ORDER BY tr.request_time DESC").arg(empId);

    QList<QString> fields = {"request_id", "old_dept_id", "new_dept_id", "reason", "request_time", "status", "old_dept_name", "new_dept_name"};
    QList<QVariantList> data;

    if (m_dbOperator->selectDataBySql(sql, fields, data)) {
        foreach (const QVariantList &row, data) {
            QVariantHash request;
            request.insert("request_id", row[0]);
            request.insert("old_dept_id", row[1]);
            request.insert("new_dept_id", row[2]);
            request.insert("reason", row[3]);
            request.insert("request_time", row[4]);
            request.insert("status", row[5]);
            request.insert("old_dept_name", row[6]);
            request.insert("new_dept_name", row[7]);
            requests.append(request);
        }

        if (!requests.isEmpty()) {
            emit operationResult(true, "查询调岗申请成功");
        } else {
            emit operationResult(false, "未找到调岗申请");
        }
    } else {
        emit operationResult(false, "查询调岗申请失败: " + m_dbOperator->lastError());
    }

    return requests;
}
